//
//  RollPictureViewController.m
//  CatMusic
//
//  Created by dllo on 15/5/1.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "RollPictureViewController.h"
#import "NetWorkingTool.h"
#import "RollPictureCell.h"
#import "UIImageView+WebCache.h"
#import "BaseModel.h"
#import "MusicPlayViewController.h"
#import "MJRefresh.h"
#import "AFNetworkReachabilityManager.h"
#import "NightMode.h"
#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height
@interface RollPictureViewController ()<UITableViewDataSource, UITableViewDelegate>
{
    NSInteger number;
}
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)NSMutableArray *tableArray;
@property(nonatomic, retain)NSMutableDictionary *dataDictionary;
@property(nonatomic, retain)NSMutableArray *playModelArray;
@property (nonatomic , retain)UIImageView *imageView;
@property (nonatomic , retain)UIView *myView;
@property(nonatomic, retain)RollPictureCell *cell;


@end

@implementation RollPictureViewController

- (void)dealloc
{
    [_cell release];
    [_myView release];
    [_imageView release];
    [_dataDictionary release];
    [_playModelArray release];
    [_tableView release];
    [_tableArray release];
    [super dealloc];
}


- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.tableArray = [NSMutableArray array];
        self.playModelArray = [NSMutableArray array];
        number = 1;

    }
    return self;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"推荐热歌";
//    [self creatTableView];
//    [self blockAsndGet];
//    [self tableViewRefresh];
//    [self addFooter];
    
    
#pragma mark - 判断网络状态    AFN
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    
    // 2.设置网络状态改变后的处理
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 当网络状态改变了, 就会调用这个block
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
                NSLog(@"未知网络");
                break;
                
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
                NSLog(@"没有网络(断网)");
                [self alertViewCancel];
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
                NSLog(@"手机自带网络");
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
                NSLog(@"WIFI");
                [self creatTableView];
                [self blockAsndGet];
                [self tableViewRefresh];
                [self addFooter];
                break;
        }
    }];
    
    // 3.开始监控
    [mgr startMonitoring];
    [self animationImage];
    
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setLightDayModel) name:@"LightDayNSNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setNightDayModel) name:@"NightDayNSNotification" object:nil];
    
//    if ([NightMode shareNightMode].isNight) {
//        [self setNightDayModel];
//    } else {
//        [self setLightDayModel];
//    }
//    
    
    
    
    
    
}

- (void)alertViewCancel
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络断开连接" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil, nil];
    [alert show];
}




- (void)animationImage
{
    self.myView = [[UIView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    self.myView.backgroundColor = [UIColor whiteColor];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(WIDTH / 2 - 40, HEIGHT / 2 - 200, WIDTH / 375 * 160, HEIGHT / 667 * 40)];
    label.text = @"努力加载中....";
    [self.myView addSubview:label];
    [label release];
    [self.view addSubview:self.myView];
    self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(WIDTH / 2 -80, HEIGHT / 2 - 80, WIDTH / 375 * 160, HEIGHT / 667 * 160)];
    [self.myView addSubview:self.imageView];
    NSMutableArray *imageArr = [NSMutableArray array];
    for (NSInteger i = 1; i < 56 ; i++) {
        NSString *imageName = [NSString stringWithFormat:@"a%ld.png" , i];
        UIImage *image = [UIImage imageNamed:imageName];
        [imageArr addObject:image];
    }
    self.imageView.animationImages = imageArr;
    self.imageView.animationDuration = 2.5;
    [self.imageView startAnimating];
    [_imageView release];
}







- (void)tableViewRefresh
{
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        [self blockAsndGet];
    }];
    
    
}





- (void)blockAsndGet
{
    
    NSString *urlString = [NSString stringWithFormat:@"http://iting.music.189.cn:9200/iting2/imusic/V2?resid=%@&page=%ld&size=6&protocolCode=2.0&method=get_user_song_single_details&sid=234472872&networkType=wifi&serviceCode=100&sessionId=83356C7DD4CDA5C8EE072C41746AA3A6&format=json&timestamp=20150423220423&sign=7a905adab1b39a007133df59f8bd232f&imsi=87D618C0-A675-458D-BB55-BED13C712771&company=&appChannelCode=10000000&appVerCode=2.000.004", self.content_id, number];
//    NSLog(@"%@--",urlString);

    [NetWorkingTool netWorkingToolStr:urlString block:^(id result) {
        NSMutableDictionary *dic = result;
        
        self.dataDictionary = [dic objectForKey:@"data"];
        
        
        NSMutableArray *songlistArray = [self.dataDictionary objectForKey:@"songlist"];
        
        for (NSMutableDictionary *listdDic in songlistArray) {
            [self.tableArray addObject:listdDic];
            
            BaseModel *playModel = [[BaseModel alloc] init];
            playModel.song_name = [listdDic objectForKey:@"song_name"];
            playModel.singer_name = [listdDic objectForKey:@"singer_name"];
//            playModel.pic_url = [listdDic objectForKey:@"singer_pic_url"];
            
            NSMutableDictionary *qqInfoDictionary = [listdDic objectForKey:@"qqInfo"];
            NSMutableDictionary *qq_url_listDic = [[qqInfoDictionary objectForKey:@"qq_url_list"] firstObject];
            NSString *urlString = [qq_url_listDic objectForKey:@"url"];
            playModel.songe_url = urlString;
            NSLog(@"%@",[listdDic objectForKey:@"singer_pic_url"]);
            if ([listdDic objectForKey:@"singer_pic_url"] == false) {
                playModel.pic_url = [listdDic objectForKey:@"singer_pic_url"];
            }else{
                playModel.pic_url = NULL;
            }
            
            [self.playModelArray addObject:playModel];
            
        }
        
        [self.tableView reloadData];
        [self.tableView.footer endRefreshing];
        [self.tableView.header endRefreshing];
        
    }];
    
    
}




- (void)creatTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    [self.tableView setDataSource:self];
    [self.tableView setDelegate:self];
    [self.view addSubview:self.tableView];
    self.tableView.rowHeight = 120;
    self.tableView.separatorStyle = UITableViewCellStyleDefault;
    [self.tableView registerClass:[RollPictureCell class] forCellReuseIdentifier:@"cell"];
    
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tableArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if ([NightMode shareNightMode].isNight) {
        [self setNightDayModel];
    } else {
        [self setLightDayModel];
    }

    self.cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    NSMutableDictionary *songlistDictionary = self.tableArray[indexPath.row];
    
    
    self.cell.songNameLabel.text  = [songlistDictionary objectForKey:@"song_name"];
    self.cell.singerLabel.text = [songlistDictionary objectForKey:@"singer_name"];
    
    
    NSNull *null = [[NSNull alloc] init];
    if ([songlistDictionary objectForKey:@"singer_pic_url"] != null) {
        NSString *singer_pic_url = [songlistDictionary objectForKey:@"singer_pic_url"];
        NSURL *url = [NSURL URLWithString:singer_pic_url];
        [self.cell.photoImage sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placeHolder"]];
        
    } else {
        [self.cell.photoImage setImage:[UIImage imageNamed:@"placeHolder"]];
    }


    [self.myView removeFromSuperview];
    return self.cell;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    MusicPlayViewController *musicPlay = [[MusicPlayViewController alloc] init];
    musicPlay.modelArr = self.playModelArray;
    musicPlay.indexPath = indexPath.row;
    [self.navigationController pushViewController:musicPlay animated:YES];
    [musicPlay release];

}

-(void)addFooter
{
    [self.tableView addLegendFooterWithRefreshingBlock:^{
            number++;
            [self blockAsndGet];
            [self.tableView reloadData];
            [self.tableView.footer endRefreshing];
    }];
}


- (void)setLightDayModel
{
    self.cell.songNameLabel.textColor = [UIColor blackColor];
    self.cell.singerLabel.textColor = [UIColor blackColor];
    [self.cell setBackgroundColor:[UIColor whiteColor]];
    [self.tableView setBackgroundColor:[UIColor whiteColor]];
    self.view.backgroundColor = [UIColor whiteColor];
    self.tabBarController.tabBar.barTintColor = [UIColor colorWithRed:245 / 255.0 green:241/ 255.0 blue:143 / 255.0 alpha:1];//////
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:245 / 255.0 green:241/ 255.0 blue:143 / 255.0 alpha:1];//////
    
    UIColor * color = [UIColor blackColor];
    //这里我们设置的是颜色，还可以设置shadow等，具体可以参见api
    NSDictionary * dict = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
    //大功告成
    self.navigationController.navigationBar.titleTextAttributes = dict;
    
    
}

- (void)setNightDayModel
{
//    self.cell.songNameLabel.textColor = [UIColor whiteColor];
//    self.cell.singerLabel.textColor = [UIColor whiteColor];
    [self.cell setBackgroundColor:[UIColor colorWithRed:38 / 255.0 green:38/ 255.0 blue:38 / 255.0 alpha:1]];
    [self.tableView setBackgroundColor:[UIColor colorWithRed:38 / 255.0 green:38/ 255.0 blue:38 / 255.0 alpha:1]];
    self.view.backgroundColor = [UIColor colorWithRed:38 / 255.0 green:38/ 255.0 blue:38 / 255.0 alpha:1];
    
    self.tabBarController.tabBar.barTintColor = [UIColor blackColor];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:38 / 255.0 green:38/ 255.0 blue:38 / 255.0 alpha:1];
    
    UIColor * color = [UIColor whiteColor];
    //这里我们设置的是颜色，还可以设置shadow等，具体可以参见api
    NSDictionary * dict = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
    //大功告成
    self.navigationController.navigationBar.titleTextAttributes = dict;
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
